package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBucketHandleBinding
import com.rzico.sbl.model.BarrelHandleData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class BucketHandleActivity : BaseActivity(R.layout.activity_bucket_handle) {

    private val mBinding by lazy { ActivityBucketHandleBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private var mBarrelTab = 0
    private var mBarrelType = ""
    private var mDateMode = "4"
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关押桶记录！"

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<BarrelHandleData>(R.layout.item_statistic_handle) { jector, bean, _ ->
                            jector.apply {
                                text(
                                    R.id.item_handle_hint,
                                    conditionIf(
                                        mBarrelTab == 1,
                                        "退桶数",
                                        "押桶数"
                                    )
                                )
                                text(R.id.item_handle_name, bean.name)
                                text(R.id.item_handle_count, bean.subQuantity)
                                text(R.id.item_handle_amount, bean.subPrice.formatDecimal())
                                text(R.id.item_handle_num, bean.n3)

                                clicked {
                                    when (mBarrelTab) {
                                        0 ->
                                            startActivityEx<BucketRecordActivity>(
                                                "barrelId" to bean.id,
                                                "barrelType" to mBarrelType,
                                                "keyword" to mKeyWord,
                                                "dateMode" to mDateMode,
                                                "beginDate" to mBeginDate,
                                                "endDate" to mEndDate
                                            )
                                        1 ->
                                            startActivityEx<BucketBackActivity>(
                                                "barrelId" to bean.id,
                                                "keyword" to mKeyWord,
                                                "dateMode" to mDateMode,
                                                "beginDate" to mBeginDate,
                                                "endDate" to mEndDate
                                            )
                                    }
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .handleSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入姓名、手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            getViewModel().mUncheckTimeList[3].isChecked = true
            handleTime.text = getViewModel().mUncheckTimeList[3].hint

            handleTypeLl.oneClick {
                getViewModel().showDropFilter(
                    getIContext(),
                    handleTop,
                    getViewModel().mBarrelList,
                    handleType,
                    handleTypeArrow
                ) {
                    handleType.setTextColor(getColorEx(R.color.colorAccent))
                    handleTypeArrow.setImageResource(R.mipmap.icon_member02)
                    handleBack.setTextColor(getColorEx(R.color.black))

                    listLayout
                        .emptyLayout
                        .emptyHint
                        .text = "暂无相关押桶记录！"

                    mBarrelTab = 0
                    mBarrelType = it.id
                    updateList()
                }
            }

            handleBack.oneClick {
                handleType.setTextColor(getColorEx(R.color.black))
                handleTypeArrow.setImageResource(R.mipmap.icon_member01)
                handleBack.setTextColor(getColorEx(R.color.colorAccent))

                listLayout
                    .emptyLayout
                    .emptyHint
                    .text = "暂无相关退桶记录！"

                getViewModel()
                    .mBarrelList
                    .forEach { it.isChecked = false }
                handleType.text = getViewModel().mBarrelList[0].hint

                mBarrelTab = 1
                mBarrelType = ""
                updateList()
            }

            handleTimeLl.oneClick {
                getViewModel()
                    .showDropTimeFilter(
                        getIContext(),
                        handleTime,
                        handleTimeArrow,
                        handleTop,
                        getViewModel().mUncheckTimeList
                    ) { bean ->

                        if (bean.id != "7")
                            getViewModel()
                                .mUncheckTimeList
                                .last()
                                .name = "自定义时间"

                        when (bean.id) {
                            "1" -> {
                                mDateMode = "1"
                                mBeginDate = getTodayDate()
                                mEndDate = getTodayDate()

                                updateList()
                            }

                            "2" -> {
                                mDateMode = "2"
                                mBeginDate = getBeforeDate()
                                mEndDate = getBeforeDate()

                                updateList()
                            }

                            "3" -> {
                                mDateMode = "3"
                                mBeginDate = getMondayDate()
                                mEndDate = getSundayDate()

                                updateList()
                            }

                            "4" -> {
                                mDateMode = "4"
                                mBeginDate = getFirstDate()
                                mEndDate = getEndDate()

                                updateList()
                            }

                            "5" -> {
                                mDateMode = "5"
                                mBeginDate = getBeforeFirstDate()
                                mEndDate = getBeforeEndDate()

                                updateList()
                            }

                            "6" -> {
                                mDateMode = "6"
                                mBeginDate = getYearFirstDate()
                                mEndDate = getYearEndDate()

                                updateList()
                            }

                            "7" -> {
                                showTimeRangeDialog(
                                    isCurrentDate = true,
                                    isAfterLimited = true,
                                    onResult = { start, end ->
                                        getViewModel()
                                            .mUncheckTimeList
                                            .forEach { it.isChecked = false }

                                        getViewModel()
                                            .mUncheckTimeList
                                            .last()
                                            .isChecked = true

                                        mDateMode = "7"
                                        mBeginDate = start
                                        mEndDate = end
                                        bean.name = "$mBeginDate ~ $mEndDate"
                                        handleTime.text = bean.name

                                        updateList()
                                    }
                                )
                            }
                        }
                    }
            }
        }
    }

    /**
     * 押桶统计列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        when (mBarrelTab) {
            0 -> {
                getViewModel()
                    .handleList(
                        page = index,
                        keyWord = mKeyWord,
                        type = mBarrelType,
                        beginDate = mBeginDate,
                        endDate = mEndDate,
                        onSuccess = {
                            mList.apply {
                                if (index == 0) {
                                    clear()
                                    pageNum = 0
                                }
                                addItems(it.data)
                                it.data.notEmpty { pageNum++ }

                                mBinding
                                    .apply {
                                        handleCount.text = it.summary?.subQuantity.orEmpty("0")
                                        handleMoney.text = it.summary?.subPrice.formatDecimal()
                                    }
                            }

                            mAdapter.setDataList(mList)
                        },
                        onFinally = {
                            isLoadingMore = false

                            mBinding
                                .listLayout
                                .apply {
                                    swipeRefresh.isRefreshing = false

                                    emptyLayout
                                        .emptyView
                                        .isVisible = mList.isEmpty()
                                }
                        }
                    )
            }

            1 -> {
                getViewModel()
                    .backList(
                        page = index,
                        keyWord = mKeyWord,
                        beginDate = mBeginDate,
                        endDate = mEndDate,
                        onSuccess = {
                            mList.apply {
                                if (index == 0) {
                                    clear()
                                    pageNum = 0
                                }
                                addItems(it.data)
                                it.data.notEmpty { pageNum++ }

                                mBinding
                                    .apply {
                                        handleCount.text = it.summary?.subQuantity.orEmpty("0")
                                        handleMoney.text = it.summary?.subPrice.formatDecimal()
                                    }
                            }

                            mAdapter.setDataList(mList)
                        },
                        onFinally = {
                            isLoadingMore = false

                            mBinding
                                .listLayout
                                .apply {
                                    swipeRefresh.isRefreshing = false

                                    emptyLayout
                                        .emptyView
                                        .isVisible = mList.isEmpty()
                                }
                        }
                    )
            }
        }
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}